import React, { useEffect, useState, useRef } from "react";
import { setSeconds } from "../utils/tools";
import "./index.scss";

function CountDown(props) {
  const { time } = props;

  const [count, setCount] = useState(time);
  const timeId = useRef({ id: 0 });

  // 启动倒计时
  const start = () => {
    timeId.current.id = window.setInterval(() => {
      setCount((count) => count - 1);
    }, 1000);
  };

  // 只执行一次，用于清除定时器
  useEffect(() => {
    start();
    return () => {
      // eslint-disable-next-line react-hooks/exhaustive-deps
      clearInterval(timeId.current.id);
    };
  }, []);

  useEffect(() => {
    if (count === 0) {
      clearInterval(timeId.current.id);
    }
  }, [count]);

  return (
    <span className="restTime">
      <span className="dd">{setSeconds(count).hourTime}</span> :{" "}
      <span className="dd">{setSeconds(count).minuteTime}</span> :{" "}
      <span className="dd">{setSeconds(count).secondTime}</span>
    </span>
  );
}

export default CountDown;
